package cn.com.css.taxInspection.workflow.controller;

import cn.com.css.taxInspection.attention.entity.Income;
import cn.com.css.taxInspection.gt3.entity.JcAyxxcxEntity;
import cn.com.css.taxInspection.gt3.entity.JcJjajEntity;
import cn.com.css.taxInspection.gt3.mapper.JcAyxxcxMapper;
import cn.com.css.taxInspection.gt3.service.JcJjajService;
import cn.com.css.taxInspection.system.controller.UserController;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import com.baomidou.mybatisplus.core.metadata.IPage;

import org.springframework.stereotype.Controller;

import cn.com.css.taxInspection.common.aop.annotation.LogAnnotation;
import cn.com.css.taxInspection.common.result.DataResult;
import cn.com.css.taxInspection.gt3.entity.JcAyxxEntity;
import cn.com.css.taxInspection.gt3.service.JcAyxxService;

import io.swagger.annotations.ApiOperation;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

import static jdk.nashorn.internal.runtime.regexp.joni.Config.log;

@Controller
@RequestMapping("/workflow/casesource")
public class WorkflowCaseSourceController {

    @Resource
    private JcAyxxService jcAyxxService;
    @Resource
    private JcAyxxcxMapper jcAyxxcxMapper;
    @Resource
    private JcJjajService jcJjajService;

    private static final Logger logger = LoggerFactory.getLogger(WorkflowCaseSourceController.class);

    @ApiOperation(value = "案源情况说明-列表")
    @LogAnnotation(title = "案源情况说明", action = "列表")
    @PostMapping("/list")
    @RequiresPermissions("workflow:casesource:list")
    @ResponseBody
    public DataResult list(@RequestBody JcAyxxEntity jcAjxxEntity) {
        IPage<JcAyxxEntity> iPage = jcAyxxService.pageInfo(jcAjxxEntity);
        return DataResult.success(iPage);
    }

    @ApiOperation(value = "工作调度-导入案件编号")
    @LogAnnotation(title = "工作调度", action = "导入案件编号")
    @PostMapping("/uploadAyxxcxExcel")
    @ResponseBody
    @DS("oracle")
    public DataResult uploadAyxxcxExcel(@RequestParam("file") MultipartFile file) {
        // 读取上传的 Excel 文件
        if (file.isEmpty()) {
            return DataResult.fail("文件为空");
        }
        try (InputStream inputStream = file.getInputStream()) {
            // 使用 Apache POI 读取 Excel 文件
            Workbook workbook = new XSSFWorkbook(inputStream);
            org.apache.poi.ss.usermodel.Sheet sheet = workbook.getSheetAt(0); // 获取第一个工作表
            // 初始化两个列表
            List<String> nsrsbhList = new ArrayList<>();
            List<String> nsrmcList = new ArrayList<>();

            // 遍历每一行（从第二行开始，跳过表头）
            for (int i = 0; i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i);
                if (row == null) continue;

                // 获取第一列的值
                Cell cell = row.getCell(0);
                if (cell != null) {
                    String value = cell.getStringCellValue().trim();
                    if (!value.isEmpty()) {
                        // 判断是否是汉字
                        if (isChinese(value)) {
                            nsrmcList.add(value); // 汉字加入纳税人名称列表
                        } else {
                            nsrsbhList.add(value); // 非汉字加入纳税人识别号列表
                        }
                    }
                }
            }
            List<JcAyxxcxEntity> ajxxList = jcAyxxcxMapper.queryJcayxxcxList(nsrsbhList, nsrmcList);

            // 提取结果中存在的 nsrsbh 和 nsrmc
            Set<String> matchedNsrsbh = ajxxList.stream()
                    .map(JcAyxxcxEntity::getNsrsbh)
                    .filter(Objects::nonNull)
                    .collect(Collectors.toSet());

            Set<String> matchedNsrmc = ajxxList.stream()
                    .map(JcAyxxcxEntity::getNsrmc)
                    .filter(Objects::nonNull)
                    .collect(Collectors.toSet());

            // 找出未匹配的 nsrsbh
            List<String> noNsrsbhList = nsrsbhList.stream()
                    .filter(nsrsbh -> !matchedNsrsbh.contains(nsrsbh))
                    .collect(Collectors.toList());

            // 找出未匹配的 nsrmc
            List<String> noNsrmcList = nsrmcList.stream()
                    .filter(nsrmc -> !matchedNsrmc.contains(nsrmc))
                    .collect(Collectors.toList());
            List<JcAyxxcxEntity> nsrxxResult = new ArrayList<>();
            // 4. 查询未匹配的记录(不带分页)
            if (!noNsrsbhList.isEmpty() || !noNsrmcList.isEmpty()) {
                nsrxxResult = jcAyxxcxMapper.queryJcayxxcxByNsrxxList(noNsrsbhList, noNsrmcList);
            }
            // 5. 合并结果并重新分页
            List<JcAyxxcxEntity> result = new ArrayList<>();
            result.addAll(ajxxList);
            result.addAll(nsrxxResult);

            logger.info("！！！！！！！！！！！！！！！！！！！！！！已有nsrsbh{}", ajxxList);
            logger.info("！！！！！！！！！！！！！！！！！！！！！！未有nsrsbh{}", nsrxxResult);

            JcAyxxcxEntity jcAyxxcxEntity = new JcAyxxcxEntity();
            Page<JcAyxxcxEntity> page = new Page<>();
            page.setRecords(result);
            page.setTotal(result.size());
            page.setCurrent(jcAyxxcxEntity.getPage());
            return DataResult.success(page);
        } catch (IOException e) {
            logger.error("文件解析失败", e);
            return DataResult.fail("文件解析失败");
        }
    }

    // 判断字符串是否以汉字为主
    private boolean isChinese(String str) {
        int chineseCount = 0;
        for (char c : str.toCharArray()) {
            if (Character.toString(c).matches("[\u4e00-\u9fa5]")) {
                chineseCount++;
            }
        }
        return chineseCount > str.length() / 2; // 汉字超过一半
    }


    @ApiOperation(value = "检举案件-导入纳税人识别号")
    @LogAnnotation(title = "检举案件", action = "导入纳税人识别号")
    @PostMapping("/uploadJjajExcel")
    @ResponseBody
    @DS("oracle")
    public DataResult uploadJjajExcel(@RequestParam("file") MultipartFile file) {
        // 读取上传的 Excel 文件
        if (file.isEmpty()) {
            return DataResult.fail("文件为空");
        }
        try (InputStream inputStream = file.getInputStream()) {
            // 使用 Apache POI 读取 Excel 文件
            Workbook workbook = new XSSFWorkbook(inputStream);
            org.apache.poi.ss.usermodel.Sheet sheet = workbook.getSheetAt(0); // 获取第一个工作表
            List<String> caseNumbers = new ArrayList<>();
            // 遍历每一行（从第二行开始，跳过表头）
            for (int i = 0; i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i);
                if (row == null) continue;
                // 获取第一列的值
                Cell cell = row.getCell(0);
                if (cell != null) {
                    String caseNumber = cell.getStringCellValue().trim();
                    if (!caseNumber.isEmpty()) {
                        caseNumbers.add(caseNumber);
                    }
                }
            }
            JcJjajEntity jcJjajEntity = new JcJjajEntity();
            IPage<JcJjajEntity> page = new Page<>(jcJjajEntity.getPage(), jcJjajEntity.getLimit());
            LambdaQueryWrapper<JcJjajEntity> queryWrapper = Wrappers.lambdaQuery();
            queryWrapper.in(JcJjajEntity::getNsrsbh, caseNumbers);
            queryWrapper.orderByDesc(JcJjajEntity::getLarq);
            IPage<JcJjajEntity> iPage = jcJjajService.page(page, queryWrapper);
            return DataResult.success(iPage);
        } catch (IOException e) {
            logger.error("文件解析失败", e);
            return DataResult.fail("文件解析失败");
        }
    }
}
